﻿using CodeGenerator.Common;
using CodeGenerator.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeGenerator
{
    public partial class frmBatch : Form
    {
        private BackgroundWorker backgroundWorker1;
        private FolderBrowserDialog folderBrowserDialog1;
        public Connection ConnectionModel
        {
            get =>
                this.connectionModel;
            set
            {
                this.connectionModel = value;
            }
        }

        public string DatabaseName
        {
            get;set;
        }
        private IDbObject dbObject;
        private string TplContent { get; set; }
        private Sysconfig sysconfigModel;
        private Connection connectionModel;

        private Dictionary<string, bool> tableview = new Dictionary<string, bool>();
        public frmBatch()
        {
            InitializeComponent();
            this.folderBrowserDialog1 = new FolderBrowserDialog();
            this.backgroundWorker1 = new BackgroundWorker();
            FileInfo[] files = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template")).GetFiles("*.tpl", SearchOption.AllDirectories);
            foreach (FileInfo info in files)
            {
                this.tplComboBox.Items.Add(info.Name);
            }
            
            string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template", this.tplComboBox.SelectedText);
            if (File.Exists(path))
            {
                this.TplContent = FileHelper.Read(path, null).ToString();
            }
            if (this.tplComboBox.Items.Count == 0)
            {
                Utils.MessageBoxShow("丢失模板文件!");
            }
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (string str in this.lbright.Items)
            {
                string className = Utils.ToCamelName(str);
                EntityBuilder builder = new EntityBuilder(str, this.txtNamaspace.Text, className, Utils.GetColumnInfos(this.dbObject.GetColumnInfoList(this.DatabaseName, str)), this.tableview[str], true, this.ConnectionModel.DbType);
                string path = this.txtPath.Text;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                using (StreamWriter writer = new StreamWriter(Path.Combine(path, className + ".cs"), false, Encoding.UTF8))
                {
                    writer.Write(builder.Builder(this.TplContent));
                    writer.Close();
                }
                this.backgroundWorker1.ReportProgress(1);
                Thread.Sleep(1);
            }
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (this.pbar.Maximum > this.pbar.Value)
            {
                this.pbar.Value++;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.btn2Allright.Enabled = true;
            this.panelbtns.Enabled = true;
            this.sysconfigModel.BatchDirectoryPath = this.txtPath.Text;
            this.sysconfigModel.Namespace = this.txtNamaspace.Text;
            Utils.WriteNamespace(this.txtNamaspace.Text);
            Utils.WriteBatchDirectoryPath(this.txtPath.Text);
           
            Utils.MessageBoxShow("生成成功!");
        }
        private void frmBatch_Load(object sender, EventArgs e)
        {
            if (this.tplComboBox.Items.Count > 0)
            {
                this.tplComboBox.SelectedIndex = 0;

            }
                this.backgroundWorker1.WorkerReportsProgress = true;
            this.backgroundWorker1.WorkerSupportsCancellation = true;
            this.backgroundWorker1.DoWork += new DoWorkEventHandler(this.backgroundWorker1_DoWork);
            this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
            this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);

            this.sysconfigModel = Utils.GetSysconfigModel();
            this.txtNamaspace.Text = this.sysconfigModel.Namespace;
            this.llServer.Text = this.connectionModel.Name;
            this.llDatabaseName.Text = this.DatabaseName;
            this.txtPath.Text = this.sysconfigModel.BatchDirectoryPath;
            DatabaseType msAccess = DatabaseType.SqlServer;

            if (this.ConnectionModel.DbType.Equals(msAccess.ToString()))
            {
                this.dbObject = new DbMSSQLObject(this.ConnectionModel.ConnectionString);
            }
            else
            {
                msAccess = DatabaseType.MySql;
                if (this.ConnectionModel.DbType.Equals(msAccess.ToString()))
                {
                    this.dbObject = new DbMySQLObject(this.ConnectionModel.ConnectionString);
                }
            }
         
            DataRow[] rowArray = this.dbObject.GetTables(this.DatabaseName).Select("", "name asc");
            if ((rowArray != null) && (rowArray.Length > 0))
            {
                foreach (DataRow row in rowArray)
                {
                    this.lbleft.Items.Add(row[0]);
                    this.tableview.Add(row[0].ToString(), false);
                }
            }
            DataRow[] rowArray2 = this.dbObject.GetVIEWs(this.DatabaseName).Select("", "name asc");
            if ((rowArray2 != null) && (rowArray2.Length > 0))
            {
                foreach (DataRow row in rowArray2)
                {
                    this.lbleft.Items.Add(row[0]);
                    this.tableview.Add(row[0].ToString(), true);
                }
            }
        }

        private void btn2Allright_Click(object sender, EventArgs e)
        {
            foreach (object obj2 in this.lbleft.Items)
            {
                this.lbright.Items.Add(obj2);
            }
            this.lbleft.Items.Clear();
        }

        private void btntoright_Click(object sender, EventArgs e)
        {
            if (this.lbleft.SelectedIndex != -1)
            {
                List<object> list = new List<object>();
                foreach (object obj2 in this.lbleft.SelectedItems)
                {
                    this.lbright.Items.Add(obj2);
                    list.Add(obj2);
                }
                foreach (object obj3 in list)
                {
                    this.lbleft.Items.Remove(obj3);
                }
            }
        }

        private void btntoleft_Click(object sender, EventArgs e)
        {
            if (this.lbright.SelectedIndex != -1)
            {
                List<object> list = new List<object>();
                foreach (object obj2 in this.lbright.SelectedItems)
                {
                    this.lbleft.Items.Add(obj2);
                    list.Add(obj2);
                }
                foreach (object obj3 in list)
                {
                    this.lbright.Items.Remove(obj3);
                }
            }
        }

        private void btn2AllLeft_Click(object sender, EventArgs e)
        {
            foreach (object obj2 in this.lbright.Items)
            {
                this.lbleft.Items.Add(obj2);
            }
            this.lbright.Items.Clear();
        }

        private void btnexport_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtNamaspace.Text))
            {
                Utils.MessageBoxShow("命名空间不能为空!");
            }
            else if (string.IsNullOrEmpty(this.txtPath.Text))
            {
                Utils.MessageBoxShow("请先选择要导出的文件夹!");
            }
            else if (!Directory.Exists(this.txtPath.Text))
            {
                Utils.MessageBoxShow("该文件夹路径不存在!");
            }
            else if (this.lbright.Items.Count == 0)
            {
                Utils.MessageBoxShow("请先选择表或视图!");
            }
            else
            {
                this.pbar.Maximum = this.lbright.Items.Count;
                this.btnexport.Enabled = false;
                this.panelbtns.Enabled = false;
                this.backgroundWorker1.RunWorkerAsync();
            }
        }

        private void btnpath_Click(object sender, EventArgs e)
        {
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.txtPath.Text = this.folderBrowserDialog1.SelectedPath;
            }
        }

        private void btncancel_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void lbleft_DoubleClick(object sender, EventArgs e)
        {
            if (this.lbleft.SelectedIndex != -1)
            {
                List<object> list = new List<object>();
                foreach (object obj2 in this.lbleft.SelectedItems)
                {
                    this.lbright.Items.Add(obj2);
                    list.Add(obj2);
                }
                foreach (object obj3 in list)
                {
                    this.lbleft.Items.Remove(obj3);
                }
            }
        }

        private void lbright_DoubleClick(object sender, EventArgs e)
        {
            if (this.lbright.SelectedIndex != -1)
            {
                List<object> list = new List<object>();
                foreach (object obj2 in this.lbright.SelectedItems)
                {
                    this.lbleft.Items.Add(obj2);
                    list.Add(obj2);
                }
                foreach (object obj3 in list)
                {
                    this.lbright.Items.Remove(obj3);
                }
            }
        }

        private void tplComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Template", this.tplComboBox.SelectedItem.ToString());
            if (File.Exists(path))
            {
                this.TplContent = FileHelper.Read(path, null);
            }
        }
    }
}
